using Autofac;
using EventBus.RabbitMQ;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;

namespace Demo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks();
            services.AddControllers();
            services.AddHostedService<TestService>();
            services.ConfigRabbitMqBus(x =>
            {
                x.HostName = "localhost";
                x.Port = 5672;
                x.UserName = "guest";
                x.Password = "guest";
                x.VirtualHost = "/";
                x.ConnectionFactoryOptions = option =>
                {
                    option.RequestedChannelMax = 10240;
                    option.RequestedConnectionTimeout = TimeSpan.FromMilliseconds(3000);
                    option.SocketReadTimeout = TimeSpan.FromMilliseconds(300000);
                    option.SocketWriteTimeout = TimeSpan.FromMilliseconds(300000);
                    option.ContinuationTimeout = TimeSpan.FromSeconds(120);
                    option.HandshakeContinuationTimeout = TimeSpan.FromSeconds(180);
                    option.RequestedFrameMax = 1024000;
                    option.RequestedHeartbeat = TimeSpan.FromSeconds(60);
                    option.AutomaticRecoveryEnabled = true;
                    option.NetworkRecoveryInterval = TimeSpan.FromSeconds(10);
                    option.TopologyRecoveryEnabled = true;
                    option.UseBackgroundThreadsForIO = true;
                    option.DispatchConsumersAsync = true;
                };
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterRabbitMqBus();
            builder.RegisterBusHandler<LoginEventHandler>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseHealthChecks("/hc");
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
